<template>
  <a-modal
    v-model="visible"
    title="绑定用户"
    :confirm-loading='confirmLoading'
    width="70%"
    style=""
    footer=''
    @cancel='cancel'>
    <a-row type="flex" :gutter="16">
      <a-col :span="10">
        <a-table rowKey="key"
                 size="middle"
                 :dataSource="departKeys"
                 :columns="column"
                 defaultExpandAllRows
                 bordered
                 :pagination="false">

        </a-table>
      </a-col>



      <a-col :span="14">
        <a-table rowKey="id"
                 size="middle"
                 :dataSource="BindUser"
                 :columns="BindUserColumn"
                 bordered
                 :pagination="false">
          <span slot="action" slot-scope="text, record">
          <a v-show='record.status===0' @click="bind(record)">绑定</a>
          <a v-show='record.status===1' @click="unbind(record)">解绑</a>
        </span>

          <div
            slot="filterDropdown"
            slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
            style="padding: 8px"
          >

            <a-input
              v-ant-ref="c => (searchInput = c)"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block;"
              @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
              @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
              type="primary"
              icon="search"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              查找
            </a-button>
            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
              重置
            </a-button>
          </div>
          <a-icon
            slot="filterIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <template slot="customRender" slot-scope="text, record, index, column">
      <span v-if="searchText && searchedColumn === column.dataIndex">
        <template
          v-for="(fragment, i) in text
            .toString()
            .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
        >
          <mark
            v-if="fragment.toLowerCase() === searchText.toLowerCase()"
            :key="i"
            class="highlight"
          >{{ fragment }}</mark
          >
          <template v-else>{{ fragment }}</template>
        </template>
      </span>
            <template v-else>
              {{ text }}
            </template>
          </template>
        </a-table>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@api/manage'

export default {
  name: "BindUserForm",
  data() {
    return {
      visible: false,
      departKeys: [],
      confirmLoading:false,
      column: [
        {
          title: '项目名称',
          dataIndex: 'title',
          align: 'left',
          key: 'key',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },

        },
        {
          title: '上级部门',
          dataIndex: 'parentName',
          align: 'center',
        },
        {
          title: '类型',
          dataIndex: "isArea",
          align: 'center',
          width: '10%',
          customRender: function (t, r, index) {
            return t === 0 ? '项目' : '部门';
          }
        }

      ],
      BindUser: [],
        BindUserColumn: [
        {
          title: '用户名',
          dataIndex: 'realName',
          align: 'center',
          width: '20%',
        },
        {
          title: '昵称',
          dataIndex: 'userName',
          align: 'center',
          width: '20%',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: '20%',
          scopedSlots: {customRender: 'action'},
        },
      ],
      searchText: '',
      searchInput: null,
      searchedColumn: '',
      url:{
        bind:"/sys/user/bind",
        unBind:"/sys/user/unBind"
      },
    }
  },
  methods: {
    bind(record){
      console.log(record);
      this.confirmLoading=true
      let formData={}
      /*无论是项目还是区域都需要进行绑定*/
      formData.userId = record.id
      /*1表示绑定的为区域，需要添加区域内所有的项目*/
      if (this.departKeys[0].isArea == 1){
        formData.projectIds = []
        formData.areaIds=[]
        this.getProjects(this.departKeys[0],formData.projectIds)
        this.getAreas(this.departKeys[0],formData.areaIds)
      }else{
        /*项目的绑定*/
        formData.depId = this.departKeys[0].value
        formData.type = this.departKeys[0].isArea
      }
      postAction(this.url.bind,formData).then((res)=>{
        if(res.success){
          this.$message.success("绑定成功")
          this.getNoBindUser(this.departKeys[0])
          this.handleOk()
        }else{
          this.$message.warn("绑定失败")
          this.getNoBindUser(this.departKeys[0])
          this.handleOk()
        }
        this.confirmLoading=false
      })
    },
    cancel(){
        this.$emit("ok")
    },
    /*遍历节点获取节点下的所有项目*/
    getProjects(departKeys,projectIds) {
      /*先判断该节点如果是项目*/

      if (departKeys.isArea==0){

        projectIds.push(departKeys.key)
      }

      if (departKeys.children!=null && departKeys.children.length>0){
        for (let i = 0; i < departKeys.children.length; i++) {
          this.getProjects(departKeys.children[i],projectIds)
        }

      }
    },
    getAreas(departKeys,areaIds){
      /*该节点是区域*/
      if (departKeys.isArea==1){

        areaIds.push(departKeys.key)
      }

      if (departKeys.children!=null && departKeys.children.length>0){
        for (let i = 0; i < departKeys.children.length; i++) {
          this.getAreas(departKeys.children[i],areaIds)
        }

      }
    },
    unbind(record){
      this.confirmLoading=false
      let formData={}
      if (this.departKeys[0].isArea == 1){
        formData.projectIds = []
        formData.areaIds=[]
        this.getAreas(this.departKeys[0],formData.areaIds)
        this.getProjects(this.departKeys[0],formData.projectIds)
      }
      formData.depId = this.departKeys[0].value
      formData.type = this.departKeys[0].isArea
      formData.userId = record.id
      postAction(this.url.unBind,formData).then((res)=>{
        if (res.success){
          this.$message.success("解绑成功")
          this.getNoBindUser(this.departKeys[0])
          // this.handleOk()
        }else{
          this.$message.warn("解绑失败")
          this.getNoBindUser(this.departKeys[0])
          // this.handleOk()
        }
      })
      this.confirmLoading=false
    },
    show(keys) {
      this.departKeys = keys
      this.getNoBindUser(this.departKeys[0])
      this.visible = true
    },
    ok(){
      this.$emit("ok")
    },
    handleOk() {
      // this.visible=false
      this.$emit("ok")
    },
    handleSearch(selectedKeys, confirm, dataIndex) {
      confirm();
      this.searchText = selectedKeys[0];
      this.searchedColumn = dataIndex;
    },

    handleReset(clearFilters) {
      clearFilters();
      this.searchText = '';
    },
    getNoBindUser(key){
      if (key.isArea === 1){
        getAction("/sys/user/getUserByCode",{orgCode:key.key}).then((res)=>{
          if (res.success){
            this.BindUser = res.result
          }
        })
      }else if (key.isArea===0){
        getAction("/sys/user/getUserByProject",{projectId:key.key,parentId:key.parentId}).then((res)=>{
            if (res.success){
              this.BindUser=res.result
            }
        });
      }
      console.log(this.BindUser)

    }
  }
}
</script>

<style scoped>

</style>